package com.wuye.interceptor;

import com.wuye.repository.WeixinTokenRepository;
import com.wuye.web.AppConfig;
import com.wuye.web.SessionHandler;
import com.wuye.weixin.Configuration;
import com.wuye.weixin.WeixinManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

//import groovy.util.logging.Commons;


/**
 * Created by jiawenlong on 2016/6/16.
 */
@Component
public class InjectFilter implements Filter {

    @Autowired
    WeixinTokenRepository weixinTokenRepository;
    @Autowired
    private SessionHandler sessionHandler;
    @Autowired
    private AppConfig appConfig;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        WeixinManager.weixinTokenRepository = weixinTokenRepository;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String ua = req.getHeader("User-Agent");
        String reqUrl = req.getRequestURI();
        if (reqUrl.indexOf("/weixinLogin.jspx") <= 0 && ua != null && ua.toLowerCase().indexOf("micromessenger") > 0 && !sessionHandler.useSessionExists(req.getSession())) {
            HttpServletResponse resp = (HttpServletResponse) response;
            String url = getLoginPageUrl(Configuration.getOAuthAppId(), appConfig.getHost()+"/weixin/weixinLogin.jspx", req.getRequestURI()+"?"+req.getQueryString());
            System.out.println("微信用户的登录授权URL=" + url);
            resp.sendRedirect(url);
            return;

        }
        filterChain.doFilter(request, response);
    }

    public String getLoginPageUrl(String appId, String returnUrl, String state) {
        try {
            return "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" + appId + "&redirect_uri=" + URLEncoder.encode(returnUrl, "UTF-8") + "&response_type=code&scope=snsapi_base" +
                    "&state=" + URLEncoder.encode(state, "UTF-8") + "#wechat_redirect";
        } catch (UnsupportedEncodingException ex) {
            return "";
        }
    }

    @Override
    public void destroy() {

    }
}
